﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.Interfaces;
using SharpObjects.RuleEngine.RuleElements;
using SharpObjects.RuleEngine;

namespace SharpObjects.RuleEngine.Rules
{
    public class IfTrueRule : IXmlInitializable, IRule
    {
        public FieldElement Field { get; set; }
        public ListOfRulesElement YesRules { get; set; }
        public ListOfRulesElement NoRules { get; set; }

        #region IInitializable Members

        public void Initialize(XmlElement initializationElement)
        {
            XmlConfigurationProvider init = new XmlConfigurationProvider(initializationElement);

            Field = init.GetObject<FieldElement>("field");
            YesRules = init.GetObject<ListOfRulesElement>("yes");
            NoRules = init.GetObject<ListOfRulesElement>("no", (ListOfRulesElement) null);

            this.IsInitialized = true;
        }

        public bool IsInitialized { get; set; }

        #endregion

        #region IRule Members

        public void Execute(ref IRuleEngineContext ruleEngineContext, IDataProvider dataProvider)
        {
            bool condition = (bool) Field.GetValue(ruleEngineContext, dataProvider);

            if(condition)
            {
                foreach(IRule rule in YesRules.Rules)
                {
                    rule.Execute(ref ruleEngineContext, dataProvider);
                }
            }
            else
            {
                foreach (IRule rule in NoRules.Rules)
                {
                    rule.Execute(ref ruleEngineContext, dataProvider);
                }
            }
        }

        #endregion
    }
}
